Wiki  - Library Entry

Singleton

GoF

Creational

Intent

Ensure a class has only one instance and provide a global point of access.

UML

Solution:

1.     Declare the constructor(s) as Protected;

2.     Declare a static self pointer to hold a reference to the single instance when it is created;

3.     Declare a static instance function which creates and returns the single instance if the self pointer is NULL, otherwise it just returns the previously created instance.

4.     Declare a protected destructor that sets the self pointer to NULL

5.     Declare other methods and attributes as needed normally.

6.     Clients access the singleton by calling the static instance function to get a reference to the single instance and then using it to call other methods.

7.     Clients must not store this instance reference -- Each code segment that needs to access the singleton should call the instance function, perform the work needed and then discard the reference as quickly as possible. 

Consequences